package com.goodluck.goodluckim.utils;

import android.app.ActivityManager;
import android.content.Context;

import java.util.ArrayList;
import java.util.List;
import java.util.ResourceBundle;

import static android.content.Context.ACTIVITY_SERVICE;

/**
 * Created by wyj on 2018/9/10.
 */

public class AndroidUtils {

    /**
     * 判断服务是否在运行
     *
     * @param context
     * @param ServiceName
     * @return
     */
    public static boolean isServiceRunning(Context context, String ServiceName) {
        if (("").equals(ServiceName) || ServiceName == null) {
            return false;
        }
        ActivityManager systemService = (ActivityManager) context.getSystemService(ACTIVITY_SERVICE);
        ArrayList<ActivityManager.RunningServiceInfo> runningService = (ArrayList<ActivityManager.RunningServiceInfo>) systemService.getRunningServices(Integer.MAX_VALUE);
        for (int i = 0; i < runningService.size(); i++) {
            if (runningService.get(i).service.getClassName().toString().equals(ServiceName)) {
                return true;
            }
        }
        return false;
    }

    /**
     * 判断app是否在运行
     *
     * @param context
     * @param packageName
     * @return
     */
    public static boolean isTaskRunning(Context context, String packageName) {
        ActivityManager activityManager = (ActivityManager) context.getSystemService(ACTIVITY_SERVICE);
        List<ActivityManager.RunningTaskInfo> list = activityManager.getRunningTasks(Integer.MAX_VALUE);
        for (int i = 0; i < list.size(); i++) {
            ActivityManager.RunningTaskInfo item = list.get(i);
            if (packageName.equals(item.topActivity.getPackageName())) {
                return true;
            }
        }
        return false;
    }

    /**
     * 当前应用是否处于前台
     *
     * @param context
     * @return
     */
    public static boolean isForeground(Context context) {
        if (context != null) {
            ActivityManager activityManager = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
            List<ActivityManager.RunningAppProcessInfo> processes = activityManager.getRunningAppProcesses();
            for (ActivityManager.RunningAppProcessInfo processInfo : processes) {
                if (processInfo.processName.equals(context.getPackageName())) {
                    if (processInfo.importance == ActivityManager.RunningAppProcessInfo.IMPORTANCE_FOREGROUND) {
                        return true;
                    }
                }
            }
        }
        return false;
    }
}
